package com.mars.basic.service;

import com.mars.basic.allmain.entity.PermissionEntity;
import com.mars.basic.allmain.po.Permission;
import com.mars.basic.allmain.po.QPermission;
import com.mars.basic.allmain.vo.PermissionVo;
import com.mars.basic.factory.PermissionFac;
import com.mars.basic.repository.PermissionRepository;
import com.mars.basic.security.config.security.dto.QtjPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PermissionService {

    final PermissionRepository userRepository;

    public PermissionRepository getPermissionRepository() {
        return userRepository;
    }


    public void addAdmin(PermissionVo dto) {
        boolean exists = getPermissionRepository().exists(QPermission.permission.name.eq(dto.getName()));
        if (!exists) {
            PermissionEntity save = getPermissionRepository().save(PermissionFac.toEntity(dto));
        }
    }

    /**
     * 根据url查询权限
     *
     * @param url
     * @return
     */
    public PermissionEntity findByUrl(String url) {
        PermissionEntity entity = getPermissionRepository().findOneIfMutil(QPermission.permission.url.eq(url));
        return entity;
    }

    /**
     * 判断该权限名称或者url是否存在
     *
     * @param vo
     * @return
     */
    public Boolean checkPermissionIsExit(PermissionVo vo) {
        boolean exists = getPermissionRepository().exists(QPermission.permission.name.eq(vo.getName()).or(QPermission.permission.url.eq(vo.getUrl())));
        return exists;
    }

    /**
     * 逻辑需要增强不能删除自己
     *
     * @param id
     * @return
     */
    public void deleteAdmin(Integer id) {
        getPermissionRepository().deleteById(id);
    }

    public PermissionEntity findById(Integer id) {
        PermissionEntity permissionEntity = getPermissionRepository().findById(id).orElse(null);
        return permissionEntity;
    }

    /**
     * 获取所有权限
     *
     * @return
     */
    public List<PermissionEntity> getAllList() {
        List<PermissionEntity> all = getPermissionRepository().findAll();
        return all;
    }

    /**
     * 获取数据库所有url
     *
     * @return
     */
    public List<String> getAllUrls() {
        List<String> urls = getAllList().stream().map(PermissionEntity::getUrl).collect(Collectors.toList());
        return urls;
    }

    /**
     * 获取全局url
     *
     * @param run
     * @return
     */
    public List<Permission> getMyUrls(ConfigurableApplicationContext run) {
        //获取restcontroller注解的类名
        String[] beanNamesForAnnotation = run.getBeanNamesForAnnotation(RestController.class);
        ArrayList<Permission> list = new ArrayList<>();
        //获取类对象
        for (String str : beanNamesForAnnotation) {
            Object bean = run.getBean(str);
            Class<?> clz = bean.getClass();
            String fullName = clz.getName();
            if (fullName.contains("EnhancerBySpringCGLIB") || fullName.contains("$$")) {
                fullName = fullName.substring(0, fullName.indexOf("$$"));
                try {
                    clz = Class.forName(fullName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
            //获取requestmapping注解的类
            RequestMapping declaredAnnotation = clz.getAnnotation(RequestMapping.class);
            //获取requestmapping注解的类
            String url_path = "";
            if (declaredAnnotation != null) {
                String[] value = declaredAnnotation.value();
                //获取类的url路径
                if (value.length > 0) {
                    url_path = value[0];
                }
                for (Method method : clz.getDeclaredMethods()) {
                    RequestMapping annotation2 = method.getAnnotation(RequestMapping.class);
                    QtjPermission annotation3 = method.getAnnotation(QtjPermission.class);

                    if (annotation2 != null && annotation2.value().length > 0) {
                        String path = url_path + annotation2.value()[0];
                        String name = "";
                        if (annotation3 != null) {
                            name = annotation3.name();
                        }
                        name = annotation2.name();
                        Permission permission = Permission.builder().url(path).name(name).build();
                        list.add(permission);
                    }
                }

            }

        }
        return list;
    }

}
